package Data_Structure.Queue;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @className: MyStack
 * @author: 芃
 * @description: 使用队列实现栈
 * @date: 2023/8/22 11:18
 */
public class MyStack {
    private Queue<Integer> queue1;
    private Queue<Integer> queue2;

    public MyStack() {
        queue1 = new LinkedList<>();
        queue2 = new LinkedList<>();
    }

    //入栈
    public void push(int x) {
        //当两个栈都为空时，默认放到queue1
        if (queue1.isEmpty() && queue2.isEmpty()){
            queue1.offer(x);
        }else if (!queue1.isEmpty()){//说明queue1不为空
            queue1.offer(x);
        }else {//说明queue1为空，queue2不为空
            queue2.offer(x);
        }
    }

    //出栈
    public int pop() {
        if (empty()){
            return -1;
        }else {
            int size = 0;
            if (!queue1.isEmpty()){
                size = queue1.size();
                for (int i = 0; i < size - 1; i++) {
                    queue2.offer(queue1.poll());
                }
                return queue1.poll();
            }else {
                size = queue2.size();
                for (int i = 0; i < size - 1; i++) {
                    queue1.offer(queue2.poll());
                }
                return queue2.poll();
            }
        }
    }

    //查看栈顶元素
    public int top() {
        if (empty()){
            return -1;
        }else {
            int size = 0;
            if (!queue1.isEmpty()){
                size = queue1.size();
                int val = -1;
                for (int i = 0; i < size; i++) {
                    val = queue1.poll();
                    queue2.offer(val);
                }
                return val;
            }else {
                size = queue2.size();
                int val = -1;
                for (int i = 0; i < size; i++) {
                    val = queue2.poll();
                    queue1.offer(val);
                }
                return val;
            }
        }
    }

    //判空 两个队列都为空时说明栈为空
    public boolean empty() {
        return queue1.isEmpty() && queue2.isEmpty();
    }
}
